package name.zxw.rabbitmq.dead;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConnectionFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangxinwang
 * @date 2022/6/23 10:04
 */
public class MyConsumer1 {

    private static final String NORMAL_EXCHANGE = "normal_exchange";
    private static final String DEAD_EXCHANGE = "dead_exchange";
    private static final String NORMAL_QUEUE = "normal_queue";
    private static final String DEAD_QUEUE = "dead_queue";
    private static final String NORMAL_ROUTING_KEY = "zhangsan";
    private static final String DEAD_ROTING_KEY = "list";


    public static void main(String[] args) throws Exception {
        //x-message-ttl
        //x-dead-letter-exchange
        //x-dead-letter-routing-key
        //x-max-length

        //durable exclusive

        ConnectionFactory factory = new ConnectionFactory();
        Channel channel = factory.newConnection().createChannel();

        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);

        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-message-ttl",10000); //消息10s后超时
        arguments.put("x-dead-letter-exchange", DEAD_EXCHANGE); //死信交换机
        arguments.put("x-dead-letter-routing-key", DEAD_ROTING_KEY); //死信路由
        arguments.put("x-max-length",4); //最大长度5

        channel.queueDeclare(NORMAL_QUEUE, false, false, false, arguments);
        channel.queueDeclare(DEAD_QUEUE, false, false, false, null);

        channel.queueBind(NORMAL_QUEUE, NORMAL_EXCHANGE, NORMAL_ROUTING_KEY);
        channel.queueBind(DEAD_QUEUE, DEAD_EXCHANGE, DEAD_ROTING_KEY);

        channel.basicConsume(NORMAL_QUEUE,
                (consumerTag, message) -> {
                    try {
                        TimeUnit.SECONDS.sleep(3);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    String msg = new String(message.getBody());
                    System.out.println("接收到消息: " + msg);
                    if (Integer.parseInt(msg) % 2 == 0) {
                        channel.basicReject(message.getEnvelope().getDeliveryTag(), false);
                    }else{
                        channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
                    }
                },
                consumerTag -> {

                }
        );


    }


}
